<template>
  <div
    v-for="c in components"
    :key="c.name"
    class="float-window"
    :style="{ left: c.pos.left + 'px', top: c.pos.top + 'px' }"
  >
    <layout-item
      :id="c.name"
      :name="c.name"
      v-bind="c.params"
      :item-uuid="c.uuid"
      @close="onItemClose"
      @attach="onItemAttach"
    ></layout-item>
  </div>
</template>

<script lang="ts" setup>
import { ref, defineExpose, nextTick } from "vue";
import {
  emitRevalidateTeleportTarget,
  setHandleRemoveComponent,
  setOnReshowRemovedComponent,
} from "./status";
import LayoutItem from "./LayoutItem.vue";
import { store } from "./store";
import { LayoutItemComponent } from "../scripts/models";
import { statusCenter } from "@/scripts/status";

const components = ref<LayoutItemComponent[]>([]);

const addComponent = (c: LayoutItemComponent) => {
  console.log(c);
  statusCenter.setLayoutComponent(c.name, c);
  components.value.push(c);
};

const onItemClose = (itemName: string) => {
  console.log(itemName);
  const index = components.value.findIndex((c) => c.name == itemName);
  if (index != -1) {
    components.value[index].posMeta = {
      type: "window-manager",
      parent: "",
      lastComponent: "",
    };
    components.value.splice(index, 1);
  }
};

setHandleRemoveComponent((uuid: string) => {
  const index = components.value.findIndex(
    (component) => component.uuid == uuid
  );
  if (index != -1) {
    components.value.splice(index, 1);
  } else {
    console.error("Cannot remove the sub component with uuid", uuid);
  }
});

setOnReshowRemovedComponent(async (targetID: string) => {
  const component = statusCenter.getLayoutComponent(targetID);
  console.log(component);
  if (
    component != null &&
    component.posMeta != null &&
    component.posMeta?.type == "window-manager"
  ) {
    store.state.hiddenTargets.delete(targetID);
    components.value.push(component);
    await nextTick();
    emitRevalidateTeleportTarget(targetID);
  }
});

const dumpWindows = () => {
  return components.value;
};
defineExpose({ addComponent, dumpWindows });
</script>

<style scoped>
.float-window {
  position: absolute;
  z-index: 300;
  border: 5px solid black;
}
</style>
